package util

import (
	jsoniter "github.com/json-iterator/go"
	"gpt-api/framework/log"
	"io/ioutil"
	"net/http"
)

func GetOpenid(code, appid string) (string, error) {
	var url string
	/*	//32ef33db01681f756a311f04c5eb02a1
		url := "https://api.weixin.qq.com/sns/oauth2/access_token?" +
			"appid=wx578bf391def34fc0" +
			"&secret=e22c87e73899eb02a5e8bf5f4d4d411c" +
			"&code=" + code + "&grant_type=authorization_code"*/
	if appid == "wx578bf391def34fc0" {
		url = "https://api.weixin.qq.com/sns/jscode2session?" +
			"appid=wx578bf391def34fc0" +
			"&secret=e22c87e73899eb02a5e8bf5f4d4d411c" +
			"&js_code=" + code + "&grant_type=authorization_code"
	} else if appid == "wxed3af43f9c77502f" {
		url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
			"appid=wxed3af43f9c77502f" +
			"&secret=32ef33db01681f756a311f04c5eb02a1" +
			"&code=" + code + "&grant_type=authorization_code"
	}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Error("get wx user openid: GET error ", log.Var("err", err))
	}

	req.Header.Add("x-platform", "")
	req.Header.Add("x-project", "")
	req.Header.Add("x-device-id", "")
	req.Header.Add("Accept-Language", "zh-CN")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Error("get wx user openid: client error ", log.Var("err", err))
	}

	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		log.Error("获取用户OPenID错误", log.Var("err", err))
	}
	var Resp struct {
		AccessToken  string `json:"access_token"`
		ExpiresIn    int    `json:"expires_in"`
		RefreshToken string `json:"refresh_token"`
		Openid       string `json:"openid"`
		Scope        string `json:"scope"`
	}
	err = jsoniter.Unmarshal(body, &Resp)
	if err != nil {
		log.Error("get wx user openid: Unmarshal err", log.Var("err", err))
	}
	return Resp.Openid, err
}
